package com.csnf.dao;

import com.csnf.entity.User;
import com.csnf.util.JdbcUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDao {

    public List<User> getAll() throws SQLException {
        Connection conn= JdbcUtil.getConnection();
        String sql="select user_id,user_name,user_nickname from user";
        PreparedStatement ps=JdbcUtil.getPreparedStatement(conn,sql);
        ResultSet rs = ps.executeQuery();
        List<User> userList = new ArrayList<>();
        while(rs.next()){
            User user=null;
            try {
                user=JdbcUtil.invokeObject(rs, User.class);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            userList.add(user);
        }
        JdbcUtil.close(rs, ps, conn);
        return userList;
    }
    public List<User> getUserByNickName(String nickName) throws SQLException{
        Connection conn= JdbcUtil.getConnection();
        String sql="select user_id,user_name,user_nickname from user where user_nickname like concat('%',?,'%')";
        PreparedStatement ps=JdbcUtil.getPreparedStatement(conn,sql,nickName);
        ResultSet rs = ps.executeQuery();
        List<User> userList = new ArrayList<>();
        while(rs.next()){
            User user=null;
            try {
                user=JdbcUtil.invokeObject(rs, User.class);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            userList.add(user);
        }
        JdbcUtil.close(rs, ps, conn);
        return userList;
    }
    public User getUserById(Integer user_id) throws Exception {
        Connection conn = JdbcUtil.getConnection();
        String sql = "select user_id,user_name,user_nickname from user where user_id=?";
        PreparedStatement ps = JdbcUtil.getPreparedStatement(conn, sql, user_id);
        ResultSet rs = ps.executeQuery();
        User user = null;
        if (rs.next()) {
            user = JdbcUtil.invokeObject(rs, User.class);
        }
        JdbcUtil.close(rs, ps, conn);
        return user;
    }
    public Boolean updateUser(User user) throws SQLException {
        String sql="update user set user_name=?,user_nickname=? where user_id=?";
        Connection conn=JdbcUtil.getConnection();
        PreparedStatement ps=JdbcUtil.getPreparedStatement(conn,sql,user.getUser_name(),user.getUser_nickname(),user.getUser_id());
        int row=ps.executeUpdate();
        JdbcUtil.close(ps, conn);
        return row>0;
    }
}
